//
//  ChatBoxVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/23.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "ChatBoxVC.h"
#import "ChatBoxFaceView.h"
#import <IQKeyboardManager.h>
#import "ChatPlusView.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "UIImage+Utils.h"
#import "CacheHelper.h"
#import <SDWebImage/SDImageCache.h>
#import "WAVideoBox.h"
#import "AddressListVC.h"
#import "SelectFileListVC.h"
#import "BaseNavigationController.h"
#import "SendCardAlert.h"

#define FaceContentView_Height 161

@interface ChatBoxVC ()<ChatBoxFaceViewDelegate, ChatBoxViewDelegate, TZImagePickerControllerDelegate>
@property (nonatomic, strong) WAVideoBox *videoBox;
@property (nonatomic, strong) ChatBoxView *boxView;
@property (nonatomic, strong) ChatBoxFaceView *faceView;
@property (nonatomic, strong) ChatPlusView *plusView;

@property (nonatomic, strong) MASConstraint *topLayoutForFaceView;
@property (nonatomic, strong) MASConstraint *topLayoutForPlusView;
@property (nonatomic, strong) MASConstraint *boxViewBottomLayoutForFaceView;
@property (nonatomic, strong) MASConstraint *boxViewBottomLayoutForPlusView;

@end

@implementation ChatBoxVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.view.backgroundColor = UIColor.whiteColor;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [IQKeyboardManager sharedManager].enable = NO;
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)setupUI {
    
    self.boxView = [ChatBoxView new];
    self.boxView.delegate = self;
    self.faceView = [[ChatBoxFaceView alloc] initWithFrame:CGRectMake(0, ScreenHeight, ScreenWidth, FaceContentView_Height+KSafeAreaBottom)];
    self.faceView.delegate = self;
    
    self.plusView = [ChatPlusView getViewFromXIB];
    [self setupMoreViewActions];
    [self.view addSubview:self.faceView];
    [self.view addSubview:self.boxView];
    [self.view addSubview:self.plusView];
    
    
    [self.boxView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        self.boxViewBottomLayoutForFaceView = make.bottom.equalTo(self.faceView.mas_top);
        self.boxViewBottomLayoutForPlusView = make.bottom.equalTo(self.plusView.mas_top);
    }];
    
    [self.faceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.mas_offset(0);
        make.height.mas_equalTo(FaceContentView_Height+KSafeAreaBottom);
        self.topLayoutForFaceView = make.top.equalTo(self.view.mas_bottom);
    }];
    [self.plusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        self.topLayoutForPlusView = make.top.equalTo(self.view.mas_bottom);
    }];
}
#pragma mark - boxView delegate
- (void)chatBox:(ChatBoxView *)boxView sendTextMsg:(NSString *)textMsg {
    
    MsgItem *msg = [MsgItem new];
    msg.content = textMsg;
    msg.type = MsgType_Text;
    [self.delegate chatBoxVC:self sendMsg:msg];
}
- (void)chatBox:(ChatBoxView *)boxView sendVoiceMsg:(NSString *)voicePath voiceDuration:(NSInteger)duration {
    
    MsgItem *msg = [MsgItem new];
    msg.second = duration;
    msg.filePath = voicePath;
    msg.type = MsgType_Voice;
    [self.delegate chatBoxVC:self sendMsg:msg];
    
}

- (void)chatBox:(ChatBoxView *)boxView changeChatBoxViewHeight:(CGFloat)height {
    if (self.boxView.status == ChatBoxStatusKeyboard) {
        self.topLayoutForFaceView.offset(-height);
        self.topLayoutForPlusView.offset(-height);
    }
    else if (boxView.status == ChatBoxStatusFace) {
        self.topLayoutForFaceView.offset(-self.faceView.height);
        self.topLayoutForPlusView.offset(0);
    }
    else if (boxView.status == ChatBoxStatusMore) {
        self.topLayoutForFaceView.offset(0);
        self.topLayoutForPlusView.offset(-self.plusView.height-KSafeAreaBottom);
    }
    else {
        self.topLayoutForFaceView.offset(0);
        self.topLayoutForPlusView.offset(0);
    }
    
    [UIView animateWithDuration:0.25 delay:0 options:7 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        if ([self.delegate respondsToSelector:@selector(chatBoxVC:didChangeChatBoxHeight:)] == YES) {
            [self.delegate chatBoxVC:self didChangeChatBoxHeight:0];
        }
    }];
}
- (void)chatBox:(ChatBoxView *)boxView changeFromStatus:(ChatBoxStatus)fromStatus toStatus:(ChatBoxStatus)toStatus {
    if (toStatus == ChatBoxStatusFace) {
        [self.boxViewBottomLayoutForFaceView activate];
        [self.boxViewBottomLayoutForPlusView deactivate];
    }
    else if (toStatus == ChatBoxStatusMore) {
        [self.boxViewBottomLayoutForFaceView deactivate];
        [self.boxViewBottomLayoutForPlusView activate];
    }
}
#pragma mark faceView delegate
- (void)chatBoxFaceViewDidSelectFace:(ChatFaceItem *)faceItem {
    [self.boxView addEmojiFace:faceItem];
}
- (void)chatBoxFaceViewDeleteBtnAction {
    [self.boxView deleteButtonDown];
}

#pragma mark more view delegate
- (void)setupMoreViewActions {
    @weakify(self);
    [self.plusView setPulsBtnActionBlock:^(NSInteger index) {
        @strongify(self);
        if (index == 0 || index == 1) {
            [self selectPhotoAndVedio:index];
        } else if (index == 2) {
            [self selectFileAction];
        } else if (index == 3) {
            [self selectFriendCardAction];
        }
        self.boxView.status = ChatBoxStatusNothing;
        [self chatBox:self.boxView changeFromStatus:0 toStatus:ChatBoxStatusNothing];
        [self chatBox:self.boxView changeChatBoxViewHeight:0];
    }];
}

- (void)selectFriendCardAction {
    AddressListVC *friendListVC = [AddressListVC new];
    @weakify(self, friendListVC);
    [friendListVC setDidSelectFriendItemBlock:^(FriendItem * _Nonnull item) {
        @strongify(self, friendListVC);
        [self sendCarMsgWithFriendInfo:item];
        [friendListVC dismissViewControllerAnimated:YES completion:nil];
    }];
    
    friendListVC.listType = 1;
    BaseNavigationController *nv = [[BaseNavigationController alloc] initWithRootViewController:friendListVC];
    [self presentViewController:nv animated:YES completion:nil];
}
- (void)selectFileAction {
    SelectFileListVC *fileListVC = [SelectFileListVC new];
    @weakify(self);
    [fileListVC setDidSelectFileBlock:^(NSString * _Nonnull fileName) {
        @strongify(self);
        
        MsgItem *msg = MsgItem.new;
        msg.type = MsgType_File;
        msg.file_name = fileName;
        msg.filePath = fileName;
        msg.file_size = [Cache_Help fileSizeWithFileName:fileName];
        
        SendCardAlert *alert = [SendCardAlert new];
        [alert showWithContent:msg.lastMsgTip toUserName:self.session.groupName?:self.friendItem.displayName toUserAvatar:self.session.groupIcon?:self.friendItem.avatar];
        @weakify(alert);
        [[alert.sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(alert);
            [alert hide];
            [self.delegate chatBoxVC:self sendMsg:msg];
            [self dismissViewControllerAnimated:YES completion:^{
                [MBProgressHUD showTipMessageInWindow:@"转发成功" timer:1.0f];
            }];
        }];
    }];
    BaseNavigationController *nv = [[BaseNavigationController alloc] initWithRootViewController:fileListVC];
    [self presentViewController:nv animated:YES completion:nil];
}

#pragma select photo
//打开相册
- (void)selectPhotoAndVedio:(BOOL)vedio
{
    TZImagePickerController *tz = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:6 delegate:nil];
    tz.allowTakePicture = YES;
    tz.allowPickingOriginalPhoto = NO;
    tz.allowPickingVideo = vedio;
    tz.allowPickingImage = !vedio;
    tz.sortAscendingByModificationDate = NO;
    //    tz.allowCrop = YES;
//    tz.photoPreviewPageDidLayoutSubviewsBlock = ^(UICollectionView *collectionView, UIView *naviBar, UIButton *backButton, UIButton *selectButton, UILabel *indexLabel, UIView *toolBar, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel) {
//        naviBar.height = 44;
//        backButton.top = 0;
//        backButton.left = 20;
//        toolBar.height = 44;
//        toolBar.bottom = ScreenHeight;
//        doneButton.right = toolBar.width - 20;
//        doneButton.top = 0;
//    };
//    NSInteger widthHeight = self.view.height - 2 * 44;
//    NSInteger top = (self.view.height - widthHeight) / 2;
//    NSInteger left = self.view.width/2 - widthHeight/2;
//    tz.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
//    // 设置横屏下的裁剪尺寸
//    tz.cropRectLandscape = CGRectMake((self.view.width - widthHeight) / 2, top, widthHeight, widthHeight);
//
//    [tz setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//        [self uploadImage:photos.firstObject];
//    }];
    tz.pickerDelegate = self;
    
    [self presentViewController:tz animated:YES completion:nil];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
//    @weakify(self);
    if (isSelectOriginalPhoto == YES) {
//        for (PHAsset *asset in assets) {
//            [[TZImageManager manager] getOriginalPhotoWithAsset:asset completion:^(UIImage *photo, NSDictionary *info) {
//                if ([info[PHImageResultIsDegradedKey] boolValue] == YES) {
//
//                }
//            }];
//        }
    } else {
        for (UIImage *img in photos) {
            NSData *smImg = [img zipToMaxSize:10];
            [self sendPhotoMsgWithImage:img smImg:smImg];
        }
    }
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    
    if (asset.duration > 30.0) {
        [LBXAlertAction showAlertWithTitle:@"提示" msg:@"您选择视频时长超过30秒，建议剪辑后再发送！ \n请进入系统相册剪辑视频" buttonsStatement:@[@"知道了"] chooseBlock:nil];
        return;
    }
    NSData *smImg = [coverImage zipToMaxSize:10];
    [MBProgressHUD showActivityMessageInWindow:@""];
    @weakify(self);
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset success:^(NSString *outputPath) {
        @strongify(self);
        NSFileManager *fileMananger = [NSFileManager defaultManager];
        NSString *fileName = [[CacheHelper helper] newFileNameForMsgType:MsgType_Video];
        NSString *suffixStr = [outputPath componentsSeparatedByString:@"."].lastObject;
        fileName = [fileName stringByAppendingFormat:@".%@",suffixStr];
        NSString *filePath = [Cache_Help allFilePathWithMsgType:MsgType_Video fileName:fileName];
        
        if (self.videoBox == nil) {
            WAVideoBox *box = [WAVideoBox new];
            box.ratio = WAVideoExportRatioMediumQuality;
            self.videoBox = box;
        }
        [self.videoBox clean];
        [self.videoBox appendVideoByPath:outputPath];
        [self.videoBox asyncFinishEditByFilePath:filePath complete:^(NSError *error) {
            [MBProgressHUD hideHUD];
            if (error != nil) {
                [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
                return ;
            }
            [fileMananger removeItemAtPath:outputPath error:nil];
            [self sendVedioMsgWithVedio:fileName smImg:smImg];
        }];
        
    } failure:^(NSString *errorMessage, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInView:errorMessage timer:1.0f];
    }];
}

- (void)sendPhotoMsgWithImage:(UIImage *)img smImg:(NSData *)smImg {
    MsgItem *msg = [MsgItem new];
    msg.s_image = [smImg base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSString *key = [[CacheHelper helper] newFileNameForMsgType:MsgType_Photo];
    [[SDImageCache sharedImageCache] storeImage:img forKey:key completion:nil];
    msg.filePath = key;
    msg.type = MsgType_Photo;
    
    [self.delegate chatBoxVC:self sendMsg:msg];
}
- (void)sendVedioMsgWithVedio:(NSString *)videoPath smImg:(NSData *)smImg {
    MsgItem *msg = [MsgItem new];
    msg.s_image = [smImg base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    msg.filePath = videoPath;
    msg.type = MsgType_Video;
    
    [self.delegate chatBoxVC:self sendMsg:msg];
}
- (void)sendCarMsgWithFriendInfo:(FriendItem *)friendItem {
    
    MsgItem *msg = [MsgItem new];
    msg.type = MsgType_Card;
    msg.content = (NSString *)friendItem;
    
    [self.delegate chatBoxVC:self sendMsg:msg];
}

@end
